<template>
    <fieldset>
        <legend>侦听器</legend>
        <input type="text" v-model="val">
        <h1>{{ props.testVal }}</h1>
        <button>点击</button>
        <button @click="handleClick2">点击2</button>
        <!-- <button @click="handleClick3">点击3</button> -->
    </fieldset>
</template>
<script setup>
import { watch, ref, defineProps, toRefs,nextTick, reactive } from "vue"
//watch

//侦听响应式变量
let val = ref("")

watch(val, (newVal, oldVal) => {
    console.log("new----", newVal)
    console.log('old-----', oldVal)
})

//侦听props
let props = defineProps(['testVal', 'testVal2'])

// console.log(props)

//1.侦听整个props
// watch(props, (newVal, oldVal) => {
//     console.log('newProp', newVal)
//     console.log('oldProp', oldVal)
// })

//2.侦听单个prop的变化
// watch(() => props.testVal, (newVal) => {
//     console.log('newVal', newVal)
// })

//3.解构的props也可以侦听

// let { testVal2 } = toRefs(props);

// watch(testVal2,(newVal)=>{
//     console.log('newTestVal2===',newVal)
// })

//侦听多个数据
// watch([()=>props.testVal,()=>props.testVal2], (newVal,oldVal) => { 
//     console.log('-----',newVal)
//     console.log('---old---',oldVal)
// })
// 侦听器函数的执行优化

// let msg1 =ref('')
// let msg2 =ref('小日子')

// let handleClick2=async()=>{ //强制触发侦听器
//     msg1.value='德国'
//     await nextTick()
//     msg2.value='日本'
// }

// watch([msg1,msg2],(newVal)=>{
//     console.log(newVal)
// })

// 6侦听对象,属性
// 深度侦听

let obj =reactive({
    name:'limei',
    age:18,
    person:{
        nickname:"卢本伟"
    }
})

setTimeout(() => {
    obj.name='韩梅梅',
    obj.person.nickname='卡卡西'
},2000);

// watch(()=>obj.person.nickname,(newVal)=>{
//     console.log(newVal);
// })
// 深度侦听&立即执行watch
watch(()=>obj.person,(newVal)=>{
    console.log(newVal);
},{
    deep:true,
    immediate:true
})
</script>